javascript


What is the DOM?

The DOM (Document Object Model) is a programming interface provided by the browser that allows JavaScript to interact with HTML and CSS. Think of it as a tree-like structure where every HTML element is a node that JavaScript can access and manipulate.


Why DOM Manipulation Matter

DOM manipulation allows you to: Change the content dynamically Respond to user actions Modify element styles and attributes Add or remove HTML elements Build interactive web apps


Accessing DOM Elements

DOM manipulation allows you to: Change the content dynamically Respond to user actions Modify element styles and attributes Add or remove HTML elements Build interactive web apps

JavaScript provides several methods to select elements:
// By ID
const title = document.getElementById('main-title');

// By Class
const items = document.getElementsByClassName('item');

// By Tag Name
const paragraphs = document.getElementsByTagName('p');

// Modern & Preferred: querySelector 
const button = document.querySelector('button');
const allItems = document.querySelectorAll('.item'); 

Interactive Button

by clicking the button ,content of the p tag will change

<html>
<head>

</head>
<body>
<button onclick="changeText()">Click Me</button>
<p id="demo">Original Text</p>

<script>
  function changeText() {
    document.getElementById('demo').textContent = 'Text Changed!';
  }
</script>
</body>
</html>
 

Adding event listener for button

example of adding the event listener for the button

<html>
<head>

</head>
<body>
<button>Click Me</button>
 
<script>
const btn = document.querySelector('button');
  btn.addEventListener('click', () => {
  alert('Button Clicked!');
});

</script>
</body>
</html>